package com.probiz.estore.core.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acegisecurity.ui.AbstractProcessingFilter;
import org.acegisecurity.ui.savedrequest.SavedRequest;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.core.util.ContextUtil;

public class LoginErrorController extends BaseController {

	public ModelAndView defaultAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
		// login error, audit event then forward to error page
		Exception e = (Exception) req.getSession().getAttribute("ACEGI_SECURITY_LAST_EXCEPTION");
		if (e != null) {
			String failedAccount = null;
			if (e instanceof org.acegisecurity.AuthenticationException) {
				try {
					failedAccount = ((org.acegisecurity.AuthenticationException) e).getAuthentication().getPrincipal().toString();
					logger.info("ACEGI failedAccount = " + failedAccount);
				} catch (Throwable t) {
					logger.error("Error retrieving login failure info from ACEGI AuthenticationException", t);
					failedAccount = "ERROR Parsing Login Name";
				}
			}

			String targetUrl = null;
			// retrieve saved requested url (saved by Acegi)
			HttpSession session = req.getSession();
			if (session != null) {
				SavedRequest sq = (SavedRequest) session.getAttribute(AbstractProcessingFilter.ACEGI_SAVED_REQUEST_KEY);
				if (sq != null) {
					targetUrl = sq.getFullRequestUrl();
				}
			}

			// if no requested url, set to use default url
			if (targetUrl == null || "".equals(targetUrl)) {
				targetUrl = req.getContextPath() + "/";
			}

			// redirect to requested url or default url
			try {

				if (ContextUtil.isStoreFront()) {
					req.getRequestDispatcher("/login.html?error=true").forward(req, resp);
				} else if (ContextUtil.isMobileFront()) {
					saveErrorMessage(req, this.getMessage("login.fail"));
					req.getRequestDispatcher("/login.html?error=true").forward(req, resp);
				} else {
					req.getRequestDispatcher("login.html?error=true").forward(req, resp);
				}
			} catch (Throwable ex) {
				logger.error("Cannot forward to error login page: " + targetUrl, ex);
			}
		}

		return null;
	}

}
